package com.neasho.neashoadminv1.infrastructure.utils

import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.MDC
import org.springframework.stereotype.Component
import org.springframework.web.servlet.AsyncHandlerInterceptor
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import java.lang.Exception

enum class MdcLogType {
    // 接口打印日志
    api,
    // 异步任务打印的日志
    task,
    // 其他
    other
}

object MDCUtils {
    const val TRACE_ID: String = "mdc_trace_id"
    const val LOG_TYPE:String = "logType"

    fun openTraceId(logType: MdcLogType): String {
        val traceId = ulid()
        MDC.put(TRACE_ID, traceId)
        MDC.put(LOG_TYPE, logType.name)
        return traceId
    }

    val traceId: String
        get() = MDC.get(TRACE_ID) ?: "none"

    val logType: String
        get() = MDC.get(LOG_TYPE) ?: MdcLogType.other.name
}

@Component
class TraceIdInterceptor : AsyncHandlerInterceptor {

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        MDCUtils.openTraceId(MdcLogType.api)
        return true
    }

    override fun afterCompletion(
        request: HttpServletRequest,
        response: HttpServletResponse,
        handler: Any,
        ex: Exception?
    ) {
        MDC.clear()
    }
}